BaseController = RouteController.extend({
  layoutTemplate:"Layout",
  loadingTemplate:'Loading',
  yieldRegions: {
    'Header': {to: 'header'}
  },
  apiServer:__meteor_runtime_config__.API_HOST,
  apiVersion:'v2',
  mainView:'',
  center:'',
  left:'',
  right:'',
  transparent:false,
  eventMap:{},
  app:null,
  $$:'',
  apiKey:'9mF/KQGoPKnbGOFbUOJ661EJ8aLNTuDW',
  apiSecret:'95D47EAD959mF/KQGoPKnbGOFbUOJ661EJ8aLNTuDW8FHY=85F8A2CD193E2300F',
  subscribeHandleDict:[],
  curUser:{},
  curUserSub:null,
  currentUserData:new ReactiveVar({}),
  subscribeCallbacks:function(){
    let self = this;
    return {
      onReady:function(){
        self.onReadyCallBack();
        return self.ready();
      },
      onStop:function(){
        self.onStopCallBack();
        self.subscribeHandle();
      }
    }
  },
  onReadyCallBack:function(){

  },
  onStopCallBack:function(){

  },
  subscribeHandle:function(){

  },
  events:function(){
    return {};
  },
  accessToken:function(){
    Meteor.subscribe('accessTokens',{},function(){
      //this.stop();
    });
  },
  on:function(event,callback){
    let self = this;
    if(!self.eventMap[event]){
      self.eventMap[event] = {};
    }
    if(!self.eventMap[event]['callbacks']){
      self.eventMap[event]['callbacks'] = {};
    }
    self.eventMap[event]['callbacks'][CryptoJS.MD5(callback.toString()).toString()] = callback;
    $(document).on(event,function(evt){
      $.each(self.eventMap[event]['callbacks'],function(idx,func){
        func({
          event:evt,
          data:self.eventMap[event]['data']
        });
      });
    });
  },
  off:function(event,callback){
    if(arguments.length == 2){
      let key = CryptoJS.MD5(callback.toString()).toString();
      delete self.eventMap[event]['callbacks'][key];
    }else{
      delete self.eventMap[event];
    }
  },
  emit:function(event,params){
    if(!this.eventMap[event]){
      this.eventMap[event] = {};
    }
    this.eventMap[event]['data'] = params;
    $(document).trigger(event);
  },
  routeParam:function(key){
    return this.params[key];
  },
  query:function(key){
    return this.params.query[key];
  },
  checkLogin:function(){

  },
  platform :function(){
    return window.platform();
  },
  now:function(){
    return (new Date()).getTime();
  },
  loginToken:function(){
    let self = this;
    let now = this.now()/1000;
    let selector = {
      '$or':[
        {
          'ttl':{
            '$gt':now
          }
        },
        {
          'refresh_ttl':{
            '$gt':now
          }
        }
      ],
      token:localStorage.token
    };
    Meteor.subscribe('loginTokens',selector,{limit:1},function(){
      if( this.ready ){
        let token = LoginToken.findOne();
        if( !token ){
          delete localStorage.token;
        }else{
          self.getCurrentUser();
        }
      }

    });
  },
  buildQuery:function(query,key){
    let self = this;
    let queryStr = ''
    if(_.isString(query) || _.isNumber(query) ||_.isNull(query)){
      queryStr = !!key ? (key+'='+query) : query;
    }else{
      if(_.isObject(query)){
        _.each(query,function(val,index){
          let tmp = '';
          if(key){
            tmp += '['+index+']';
          }else{
            tmp = index;
          }
          queryStr += '&'+self.buildQuery(val,tmp);
        });
      }else{
        queryStr =  '';
      }
    }
    return queryStr;
  },
  get:function(url,query){
    let self = this;
    query = self.buildQuery(query,'');
    if(query){
      query ='?' + query.substr(1);
    }
    return new  Promise(function(resolve,reject){
      HTTP.get(self.apiServer+"/"+self.apiVersion+"/"+url+query,function(error,result){
        if(error){
          reject(error);
        }else{
          resolve(result);
        }
      });
    });
  },
  post:function(url,data){
    let self = this;
    return new  Promise(function(resolve,reject){
      HTTP.post(self.apiServer+"/"+self.apiVersion+"/"+url,{
        data:data
      },function(error,result){
        if(error){
          reject(error);
        }else{
          resolve(result);
        }
      });
    });
  },
  put:function(url,data,callback){
    let self = this;
    return new  Promise(function(resolve,reject){
      HTTP.put(self.apiServer+"/"+self.apiVersion+"/"+url,{
        data:data
      },function(error,result){
        if(error){
          reject(error);
        }else{
          resolve(result);
        }
      });
    });
  },
  delete:function(id,callback){
    let self = this;
    return new  Promise(function(resolve,reject){
      HTTP.del(self.apiServer+"/"+self.apiVersion+"/"+url,function(error,result){
        if(error){
          reject(error);
        }else{
          resolve(result);
        }
      });
    });
  },
  onBeforeAction:function(){
    if( !window.app ){
      window.app = new Framework7({
        pushState: true,
        swipePanel: 'left',
        modalTitle: "提示",
        modalButtonOk: "确定",
        modalButtonCancel: "取消",
      });
    }
    this.app = window.app;
    if( !window.$$ ){
      window.$$ = Dom7;
    }
    this.$$ = window.$$;
    Template[this.template].onRendered(this.renderCallback);
    Template[this.template].events(this.events(this));
    let next = this.beforeAction();
    return !!next ? next() : '';
  },
  beforeAction:function(){
    return this.next;
  },
  renderCallback:function(){
    let controller = Iron.controller();
    //controller.emit('header.reset');
    if(Template.Header.url)Template.Header.url.set(controller.headerBack);
    if(Template.Header.center)Template.Header.center.set( Spacebars.SafeString(controller.center));
    if(Template.Header.left)Template.Header.left.set( Spacebars.SafeString(controller.left));
    if(Template.Header.right)Template.Header.right.set( Spacebars.SafeString(controller.right));
    let transparent = !!controller.headerTransparent ? 'transparent mask' : '';
    if(Template.Header.transparent)Template.Header.transparent.set( transparent);
    $('#views').removeAttr('class');
    $('#views').addClass("views "+controller.platform()+" "+ controller.mainView);
    let self = this;
    //controller.location.configure({useHashPaths: true});
    controller.onRendered(controller);
  },
  onRendered:function(self){
    console.log('render template');
  },

  waitOn:function(){
    let meteor = '';
    //if(AccessToken.find().count() == 0)
    meteor = this.accessToken();
    //   return meteor;
    //if(LoginToken.find().count() == 0)
    meteor = this.loginToken();
    //this.wait();
    return meteor;
  },
  wait:function(){
  },
  paging:function(collection_name,selector,sort,perpage,maxitem){
    var myApp = new Framework7;
    var $$ = Dom7;
    var self = this;
    var loading = false;
    var perpages = perpage || 4;
    var maxItems = maxitem || 8;
    var sorts = sort || {id:-1};
    var selectors = selector || {};
    var curlistLenght = 0;
    this.lastIndex = perpages || 10;
    console.log(collection_name);
    $$('.infinite-scroll').on('infinite', function(){
      var listLenght = $$('.list-block li').length;
      if(listLenght > curlistLenght){
        curlistLenght = listLenght;
      }
      if(loading)return;
      loading = true;
      setTimeout(function(){
        loading = false;
        if(self.lastIndex > curlistLenght){
          //myApp.detachInfiniteScroll($$('.infinite-scroll'));
          $('.infinite-scroll-preloader').remove();
          return;
        }
        let subscribeName = collection_name.toString();
        self.lastIndex = self.lastIndex + perpages;
        if(typeof self.subscribeHandleDict[subscribeName] != 'undefined'){
          if(self.subscribeHandleDict[subscribeName]){
            self.subscribeHandle = function(){
              self.subscribeHandleDict[subscribeName] = Meteor.subscribe(subscribeName,selectors,{sort:sorts,limit:self.lastIndex},self.subscribeCallbacks());
            }
            self.subscribeHandleDict[subscribeName].stop();
          }
          return self.subscribeHandleDict[subscribeName];
        }else{
          return Meteor.subscribe(subscribeName,selectors,{sort:sorts,limit:self.lastIndex},function(){
            return self.ready();
          });
        }
      },100)
    });
  },


  getDateStr:function(now, addDayCount) {
    now.setDate(now.getDate()+addDayCount);//获取AddDayCount天后的日期
    var y = now.getFullYear();
    var m = ("0" + (now.getMonth() + 1)).slice(-2);//获取当前月份的日期
    var d = ("0" + now.getDate()).slice(-2);
    now.setDate(now.getDate()-addDayCount);
    return y+"-"+m+"-"+d;
  },
  getRealTime:function(now ,addDayCount){
    var today = this.getDateStr(now, addDayCount);
    var hour = ("0" + now.getHours()).slice(-2);
    var minute = ("0" + now.getMinutes()).slice(-2);
    var second = ("0" + now.getSeconds()).slice(-2);
    return today+" "+(hour)+":"+(minute)+":"+(second);
  },
  getDateStart:function(now, addDayCount){
    return this.getDateStr(now, addDayCount)+" 00:00:00";
  },

//当type默认等于1的时，为本地调试模式，从本地取数据；
//		默认等于0的时,为线上运行模式,从线上取数据
  currentUser:function(){
  	var type = 0;
  	
	if (type){
		console.log("current data from localhost");
		return {
		 "id": 66,
         "real_name": "陈伟光3",
         "mobile": "15705607680",
         "province_code": 130000,
         "city_code": 130100,
         "district_code": 130102,
         "university_code": 1111,
         "college_code": 2222,
         "major_code": 3333,
         "grade": 2012,
         "class": 255,
         "sex": "male",
         'head_image':{
           'path':'https://37test.oss-cn-hangzhou.aliyuncs.com/upload/17-08-18/b0ecc4222dc0d1fb4215d9472cf40a81.jpg'
         },
         "state": "enable",
         "level": 1,
         "created_at": "2017-08-18 16:59:11",
         "updated_at": "2017-08-18 17:20:07",
         "user_base_id": 264,
         "head_img_id": 151,
         "province_name": "河北省",
         "city_name": "石家庄",
         "district_name": "长安区",
         "university_name": "河北大学",
         "college_name": "计算机学院",
         "major_name": "计算机科学",
         "level_name": "company",
         "parent_id": 0,
         "monitor_orders": [

         ],
         "platoon_orders": [

         ],
         "company_orders": [

         ],
         "register_time": {
           "date": "2017-08-18 16:59:10.000000",
           "timezone_type": 3,
           "timezone": "UTC"
         },
         "user_name": "chenwggg4"
		}
	}else{
		console.log('get data from online');
		return this.currentUserData ? this.currentUserData.get() : null;
	}
},
  
  getCurrentUser(){
    let self = this;
    Meteor.call('auth',localStorage.token,function(error,result){
      if(!error){
        if(result){
          console.log('partner id '+result);
          if(!self.curUserSub){
            console.log(self.curUserSub);
            self.curUserSub = Meteor.subscribe('curUser',result,function(){

              self.curUser = Partners.findOne({id:result});
              self.currentUserData.set(self.curUser);
            });
          }

        }
      }
    });
  },
  dateToTime(date){
    var d= new Date(Date.parse(date.replace(/-/g, "/")));
    return d.getTime()/1000;
  }
});
